<?php


namespace liuqiang;


class ExcelCsv
{
    /**
     * @var
     */
    private $titles = [];

    /**
     * @var
     */
    private $headers = [
        'Content-Type:text/html; charset=UTF-8',
        'Content-Type: application/vnd.ms-excel',
        'Cache-Control: max-age=0',
    ];

    /**
     * @var string
     */
    private $charset = 'UTF-8';

    private $fileName = [];
    /**
     * @var
     */
    private $fp;


    public function __construct($fileName)
    {
        set_time_limit(0);
        ini_set('memory_limit', '256M');
        $this->setCharset($this->charset);
        array_push($this->fileName, 'Content-Disposition: attachment;filename="' . $fileName . '.csv"');
        return $this;
    }

    /**
     * @param string $charset
     * @return $this
     * 设置字符集
     */
    public function setCharset($charset)
    {
        $this->charset = $charset;
        return $this;
    }

    /**
     * @param array $title
     * @return $this
     */
    public function setTitle(array $title)
    {
        $this->titles = $title;
        return $this;
    }

    /**
     * @param array $header
     * @return $this
     */
    public function setHeader(array $header = [])
    {
        if (!empty($header)) {
            $this->headers = $header;
        }
        return $this;
    }

    /**
     * @return $this
     * @throws \Exception
     * 开始准备初始化
     */
    public function startInit()
    {
        if (!count($this->headers)) {
            throw new \Exception('请设置 header');
        }
        if (!count($this->titles)) {
            throw new \Exception('请设置 title');
        }
        $header = array_merge($this->headers, $this->fileName);
        foreach ($header as $h) {
            header($h);
        }
        $this->fp = fopen('php://output', 'w');
        fwrite($this->fp, chr(0xEF) . chr(0xBB) . chr(0xBF));
        if ($this->charset) {
            foreach ($this->titles as &$title) {
                $title = mb_convert_encoding($title, $this->charset);
            }
        }
        fputcsv($this->fp, $this->titles);
        return $this;
    }

    /**
     * @param array $data
     */
    public function addData(array $data)
    {
        foreach ($data as $item) {
            mb_convert_encoding($item, $this->charset);
            fputcsv($this->fp, $data);
            unset($datum);
        }
        $this->flush();
    }

    /**
     *刷新缓存
     */
    public function flush()
    {
        ob_flush();
        flush();
    }

}
